//
//  THSuggestViewController.m
//  TreeHole
//
//  Created by apple on 2020/9/9.
//  Copyright © 2020 stoneobs. All rights reserved.
//

#import "THAddVideoViewController.h"
#import "STTools_TextView.h"
@interface THAddVideoViewController ()
@property(nonatomic, strong) STTools_TextView                     *text_view;/**<  */

@property(nonatomic, strong) NSMutableArray<NSArray*>                     *dataSouce;/**<  */
@property(nonatomic, strong) NSString                     *is_show;/**< 是否显示 */
@property(nonatomic, strong) NSString                     *posts_cate_id;/**< 分类id */
@property(nonatomic, strong) NSString                     *goods_id;/**<  */

@property(nonatomic, strong) NSString                     *image_url;/**<  */
@property(nonatomic, strong) NSString                     *video_url;/**<  */

@property(nonatomic, strong) STButton                     *addButton;/**<  */
@property(nonatomic, strong) STTools_MenuControl                     *menu;/**<  */
@end

@implementation THAddVideoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.is_show = @"1";
    self.title = @"拍视频";
    self.tableView.backgroundColor = UIColor.whiteColor;
    [self config_tableHeader];
    [self config_dataSouce];
    [self stoneobs_fun_st_setRightItemWithTitle:@"发布" titleColor:STONEOBS_UI_FIRST_TEXT_COLOR];
    
    if ([self.model.url containsString:@"mp4"]) {
        self.video_url = self.model.url;
        self.image_url = self.model.imgs.firstObject;
        [self.addButton sd_setImageWithURL:self.image_url.mj_url forState:UIControlStateNormal];
        self.menu.hidden = YES;
        self.text_view.text = self.model.title;
        
        ({
            STTools_TableEasyModel * model = self.dataSouce[0].firstObject;
            model.detailString =  self.model.posts_cate_name;
            self.posts_cate_id = self.model.posts_cate_id;
        });
        ({
            STTools_TableEasyModel * model = self.dataSouce[0][1];
            model.detailString =  self.model.goods_name;
            self.goods_id = self.model.goods_id;
        });
        ({
            STTools_TableEasyModel * model = self.dataSouce[0][2];
            if (self.model.is_show) {
                model.detailString =  @"所有人";
                self.is_show = @"1";
            }else{
                model.detailString =  @"自己";
                self.is_show = @"0";
            }
        });
        [self.tableView reloadData];
        
    }
    // Do any additional setup after loading the view.
}
- (void)config_dataSouce{
    self.dataSouce = NSMutableArray.new;

    ({
       NSArray * array = @[
           [[STTools_TableEasyModel alloc] initWithTextString:@"分类" detailString:@"请选择"],
           [[STTools_TableEasyModel alloc] initWithTextString:@"添加购买体验" detailString:@"请选择"],
           [[STTools_TableEasyModel alloc] initWithTextString:@"谁可以看" detailString:@"所有人"],
       ];
        [self.dataSouce addObject:array];
    });
    
    [self.tableView reloadData];
}
#pragma mark --configSubView
- (void)config_tableHeader{
    UIView * header = [[UIView alloc] initWithFrame:STONEOBS_UI_UISCREEN_FRAME];
    
    CGFloat top = 10;
    
    UIView * whiteView = [[UIView alloc] initWithFrame:CGRectMake(12, top, 200, 180)];
    whiteView.backgroundColor = WH_UICOLOR_FROM_RGBA(0xEEEEEE);
    whiteView.layer.cornerRadius = 8;
    whiteView.clipsToBounds = YES;
    [header addSubview:whiteView];
    if (!self.text_view) {
        self.text_view = [[STTools_TextView alloc] initWithFrame:CGRectMake(10, 10, whiteView.width - 20, 170)];
        self.text_view.placeholder = @"..正文";
        self.text_view.label.left = 15;
        self.text_view.label.top = 5;
        self.text_view.backgroundColor = UIColor.clearColor;
    }
    [whiteView addSubview:self.text_view];
    
    CGFloat witdh = UISCREEN_WIDTH - whiteView.right - 24;
    STButton * stoneobs_ui_button = [[STButton alloc] initWithFrame:CGRectMake(whiteView.right+12, top, witdh, 180)
                                                              title:nil
                                                         titleColor:nil
                                                          titleFont:0
                                                       cornerRadius:8
                                                    backgroundColor:whiteView.backgroundColor
                                                    backgroundImage:nil
                                                              image:nil];
    [header addSubview:stoneobs_ui_button];
    stoneobs_ui_button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [[stoneobs_ui_button imageView] setContentMode:UIViewContentModeScaleAspectFill];
    stoneobs_ui_button.contentHorizontalAlignment= UIControlContentHorizontalAlignmentCenter;
    stoneobs_ui_button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    self.addButton = stoneobs_ui_button;
    
    STTools_MenuControl * menu = [[STTools_MenuControl alloc] initWithFrame:CGRectMake(0, 0, witdh, 55) imageName:@"图片" title:@"视频" titleColor:STONEOBS_UI_THIRD_TEXT_COLOR imageHeight:25 lableHeight:30];
    menu.centerY = stoneobs_ui_button.height / 2;
    menu.userInteractionEnabled = NO;
    [stoneobs_ui_button addSubview:menu];
    menu.tag = 10001;
    __weak typeof(self) weakSelf =  self;
    [stoneobs_ui_button setClicAction:^(UIButton *sender) {
        [weakSelf stoneobs_fun_on_selcted_video_button:sender];
    }];
    self.menu = menu;

    
    header.height = stoneobs_ui_button.bottom + 10;
    self.tableView.tableHeaderView = header;
}

#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce[section].count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 20;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    [cell setSt_tableEasyModel:model];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    STTools_TableEasyModel * model = self.dataSouce[indexPath.section][indexPath.row];
    __weak typeof(self) weakSelf =  self;
    if ([model.textString isEqualToString:@"分类"]) {
        [self stoneobs_fun_st_showActionSheet:@[@"广场",@"视频",@"取消"] andWithBlock:^(int tag) {
            NSString * type = @"1";
            if (tag == 1) {
                type = @"2";
            }
            if (tag == 2) {
                return;
            }
            [THTreeHoleDataController stoneobs_fun_get_home_cates_type:type handle:^(NSArray * _Nonnull cates) {
                NSArray * cates_name = [cates stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
                STTools_PickerViewController * picker = [[STTools_PickerViewController alloc] initWithPickerArray:@[cates_name] andWithHandle:^(NSArray<NSString *> *stringArray) {
                   
                    NSString * chosed_name = stringArray.lastObject;
                    NSInteger index = [cates_name indexOfObject:chosed_name];
                    THTieZiCateModel * smodel = cates[index];
                    self.posts_cate_id = smodel.t_id;
                    model.detailString = chosed_name;
                    [self.tableView reloadData];
                }];
                [self presentViewController:picker animated:NO completion:nil];
            }];
        }];

    }
    if ([model.textString isEqualToString:@"谁可以看"]) {
        NSArray * array = @[@"自己",@"所有人"];
        STTools_ActionSheet * sheet = [STTools_ActionSheet stoneobs_fun_actionSheetWithTitle:@"谁可以看" buttonTitles:array cancelTitle:@"取消" handle:^(NSInteger index) {
            weakSelf.is_show = @(index).description;
            model.detailString = array[index];
            [weakSelf.tableView reloadData];
        }];
        [sheet show];
    }
    if ([model.textString isEqualToString:@"添加购买体验"]) {
        
        //获取已购商品
        [THTreeHoleDataController stoneobs_fun_get_did_buy_goos:^(NSArray * _Nonnull cates) {
            NSArray * cates_name = [cates stoneobs_fun_arrayFromObjKeyName:@"obj.name"];
            if (cates_name.count == 0) {
                [SVProgressHUD showInfoWithStatus:@"您暂未购买任何商品哟"];
                return;
            }
            STTools_PickerViewController * picker = [[STTools_PickerViewController alloc] initWithPickerArray:@[cates_name] andWithHandle:^(NSArray<NSString *> *stringArray) {
               
                NSString * chosed_name = stringArray.lastObject;
                NSInteger index = [cates_name indexOfObject:chosed_name];
                THTieZiCateModel * smodel = cates[index];
                self.goods_id = smodel.t_id;
                model.detailString = chosed_name;
                [self.tableView reloadData];
            }];
            [self presentViewController:picker animated:NO completion:nil];
        }];
        
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
- (void)stoneobs_fun_on_selcted_video_button:(UIButton*)sender{
    __weak typeof(self) weakSelf =  self;
    if (self.image_url.length) {
        NSArray * array = @[@"查看",@"重新选择"];
        STTools_ActionSheet * sheet = [STTools_ActionSheet stoneobs_fun_actionSheetWithTitle:@"操作" buttonTitles:array cancelTitle:@"取消" handle:^(NSInteger index) {
            if (index == 0) {
                STTools_VideoPlayViewController * vc = STTools_VideoPlayViewController.new;
                vc.url = weakSelf.video_url;
                vc.img_url = weakSelf.image_url;
                [weakSelf pushViewController:vc animated:YES];
                
            }else{
                [weakSelf chose_video_form_alblm:sender];
            }
        }];
        [sheet show];
    }else{
        [self chose_video_form_alblm:sender];
    }
}
- (void)chose_video_form_alblm:(UIButton*)sender{
    TZImagePickerController * vc = TZImagePickerController.new;
    vc.allowPickingVideo = YES;
    vc.allowPickingImage = NO;
    vc.allowTakeVideo = YES;
    vc.maxImagesCount = 1;
    vc.barItemTextColor = STONEOBS_UI_FIRST_TEXT_COLOR;
    vc.statusBarStyle = UIStatusBarStyleDefault;
    __weak typeof(self) weakSelf =  self;
    [vc setDidFinishPickingVideoHandle:^(UIImage *coverImage, id asset) {
        [SVProgressHUD showWithStatus:@"请稍后"];
        [[TZImageManager manager] getVideoOutputPathWithAsset:asset success:^(NSString *outputPath) {
            DDLogInfo(@"视屏导出成功:%@",outputPath);
            [SVProgressHUD showWithStatus:@"请稍后"];
            [TMQNUploadManger.manger sendFileWithFilePath:outputPath type:@".mp4" handle:^(NSString * _Nonnull videourl) {
                if (videourl.length) {
                    [TMQNUploadManger.manger sendQiNiuWithImage:coverImage handle:^(NSString * _Nonnull url) {
                        [SVProgressHUD dismiss];
                        if (url.length) {
                            self.image_url = url;
                            self.video_url = videourl;
                            [[sender viewWithTag:10001] removeFromSuperview];
                            [sender setBackgroundImage:coverImage forState:UIControlStateNormal];
                            sender.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
                            [[sender imageView] setContentMode:UIViewContentModeScaleAspectFill];
                            sender.contentHorizontalAlignment= UIControlContentHorizontalAlignmentCenter;
                            sender.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
                        }else{
                            [SVProgressHUD showErrorWithStatus:@"上传失败"];
                        }

                    }];
                }else{
                    [SVProgressHUD dismiss];
                    [SVProgressHUD showErrorWithStatus:@"上传失败"];
                }
            }];

        } failure:^(NSString *errorMessage, NSError *error) {
            
        }];
        
        
    }];
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}
- (void)stoneobs_fun_st_rightBarAction:(id)sender{
    if (self.text_view.text.length) {
    }else{
        [SVProgressHUD showInfoWithStatus:@"请输入正文"];
        return;
    }
    if (!self.posts_cate_id.length) {
        [SVProgressHUD showInfoWithStatus:@"请选择分类"];
        return;;
    }
    if (!self.image_url.length) {
        [SVProgressHUD showInfoWithStatus:@"请选择视频"];
        return;
    }
    [self send_add_video_request];
}
- (void)send_add_video_request{
    if (self.model) {
        [self send_update_request];
        return;
    }
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.image_url.length) {
        [stoneobs_net_param_dic setObject:@[self.image_url].mj_JSONString forKey:@"imgs"];
    }
    if (self.video_url.length) {
        [stoneobs_net_param_dic setObject:self.video_url forKey:@"url"];
    }
    
    if (self.text_view.text.length) {
        [stoneobs_net_param_dic setObject:self.text_view.text forKey:@"title"];
    }
    if (self.goods_id.length) {
        [stoneobs_net_param_dic setObject:self.goods_id forKey:@"goods_id"];
    }
    [stoneobs_net_param_dic setObject:@"2" forKey:@"type"];//类型 1 =>咨询 2=>视频
    [stoneobs_net_param_dic setObject:self.is_show forKey:@"is_show"];
    [stoneobs_net_param_dic setObject:self.posts_cate_id forKey:@"posts_cate_id"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/publish"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"发布成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
- (void)send_update_request{
    NSMutableDictionary * stoneobs_net_param_dic = [NSMutableDictionary new];
    NSString * stoneobs_net_user_id = [STTools_UserManger defult].stoneobs_fun_get_loginedUser.uid.description;
    NSString * stoneobs_net_user_token = STTools_UserManger.defult.stoneobs_fun_get_loginedUser.token;
    if (stoneobs_net_user_id.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_id forKey:@"uid"];
    }
    if (stoneobs_net_user_token.length) {
        [stoneobs_net_param_dic setObject:stoneobs_net_user_token forKey:@"token"];
    }
    if (self.image_url.length) {
        [stoneobs_net_param_dic setObject:@[self.image_url].mj_JSONString forKey:@"imgs"];
    }
    if (self.video_url.length) {
        [stoneobs_net_param_dic setObject:self.video_url forKey:@"url"];
    }
    if (self.text_view.text.length) {
        [stoneobs_net_param_dic setObject:self.text_view.text forKey:@"title"];
    }

    if (self.goods_id.length) {
        [stoneobs_net_param_dic setObject:self.goods_id forKey:@"goods_id"];
    }
    if (self.model.t_id.length) {
        [stoneobs_net_param_dic setObject:self.model.t_id forKey:@"id"];
        
    }
    [stoneobs_net_param_dic setObject:@"2" forKey:@"type"];//类型 1 =>咨询 2=>视频
    [stoneobs_net_param_dic setObject:self.is_show forKey:@"is_show"];
    [stoneobs_net_param_dic setObject:self.posts_cate_id forKey:@"posts_cate_id"];
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSString * stoneobs_net_net_url = [NSString stringWithFormat:@"%@%@",RELEASE_SERVER_URL_HEADER,@"v1/posts/edit"];
    DDLogInfo(@"url:%@",stoneobs_net_net_url);
    DDLogInfo(@"param:%@",stoneobs_net_param_dic);
    [[STTools_NetWrokManger defaultClient] stoneobs_fun_requestWithPath:stoneobs_net_net_url
                                                                 method:STHttpRequestType_stoneobs_enumPost
                                                             parameters:stoneobs_net_param_dic
                                                                success:^(NSURLSessionDataTask *operation, id responseObject) {
        [SVProgressHUD dismiss];
        NSDictionary * stoneobs_net_model_dic = [responseObject valueForKey:@"data"];
        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        });
        // DDLogInfo(@"json = \n%@",modelDic.mj_JSONString);
        DDLogInfo(@"%@请求成功:resp\n%@",stoneobs_net_net_url,responseObject);
        
        
    } failure:^(NSString *stateCode, STTools_Error *error,NSError *originError) {
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:error.desc];
        DDLogError(@"\n请求失败:\nurl:%@\nparam:%@\n失败原因:%@\n错误码:%ld",
                   stoneobs_net_net_url,stoneobs_net_param_dic,error.desc,error.code);
    }];
}
@end
